package com.domainchen.framework.core.proxy.transaction;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.domainchen.framework.common.persistence.DataBaseHepper;
import com.domainchen.framework.core.annotation.Transaction;
import com.domainchen.framework.core.proxy.Proxy;
import com.domainchen.framework.core.proxy.ProxyChain;

/**
 * @author domainchen or cytxiamen@163.com
 * @version 创建时间：2016年3月15日 下午3:54:51
 * @类说明 事务切面
 */
public class TransactionProxy implements Proxy {

	private static Logger logger = LoggerFactory.getLogger(TransactionProxy.class);

	private static ThreadLocal<Boolean> FLAG_HOLDER = new ThreadLocal<Boolean>() {
		@Override
		protected Boolean initialValue() {
			// TODO Auto-generated method stub
			return false;
		}
	};

	@Override
	public Object doProxy(ProxyChain proxyChain) throws Throwable {
		Object result = null;
		Boolean flag = FLAG_HOLDER.get();
		Method targetMethod = proxyChain.getTargetMethod();
		if (!flag && targetMethod.isAnnotationPresent(Transaction.class)) {
			FLAG_HOLDER.set(true);
			try {
				DataBaseHepper.beginTransaction();
				logger.debug("begin transaction");
				result=proxyChain.doProxyChain();
				DataBaseHepper.commitTransaction();
				logger.debug("commit transaction");
			} catch (Exception e) {
				DataBaseHepper.rollBackTransaction();
				logger.debug("rollback transaction");
				throw e;
			} finally {
				FLAG_HOLDER.remove();
			}
		}
		return result;
	}

}
